package ex05.pyrmont.core;

import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.Request;
import org.apache.catalina.Response;
import org.apache.catalina.Valve;
import org.apache.catalina.ValveContext;
import org.apache.catalina.Contained;
import org.apache.catalina.Container;

/**
 *
 *    wrapperPineLine  的 最终实现 ;  就是在这里, 将会调用 wrapper.allocate() 去调用  servlet类 ;
 *
 * */
public class SimpleWrapperValveV5 implements Valve, Contained {

    protected Container container;

    public void invoke(Request request, Response response, ValveContext valveContext) throws IOException, ServletException {

        SimpleWrapperV5 wrapper = (SimpleWrapperV5) getContainer();
        ServletRequest servletRequest = request.getRequest();
        ServletResponse servletResponse = response.getResponse();
        Servlet servlet;
        HttpServletRequest httpServletRequest = null;
        if (servletRequest instanceof HttpServletRequest) {

            httpServletRequest = (HttpServletRequest) servletRequest;
        }
        HttpServletResponse httpServletResponse = null;
        if (servletResponse instanceof HttpServletResponse) {
            httpServletResponse = (HttpServletResponse) servletResponse;
        }

        // Allocate a servlet instance to process this request
        try {
            servlet = wrapper.allocate();
            if (httpServletResponse != null && httpServletRequest != null) {
                servlet.service(httpServletRequest, httpServletResponse);
            } else {
                servlet.service(servletRequest, servletResponse);
            }
        } catch (ServletException e) {
            System.out.println("ERROR  " + e.getMessage());
        }
    }

    public String getInfo() {
        return null;
    }

    public Container getContainer() {
        return container;
    }

    public void setContainer(Container container) {
        this.container = container;
    }
}
